package com.cne.gmail.Gmail.imp;



import com.cne.gmail.Gmail.model.UserModel;
import com.cne.gmail.Gmail.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private MongoTemplate mongoTemplate;
    //单条插入数据
    @Override
    public void insert(UserModel user) {
        mongoTemplate.insert(user, "gmailUserMessage");

    }
    //根据emailAddress查询当前是否有人登陆google账号
    @Override
    public  UserModel getUser(String emailAddress) {
        Criteria criteria = Criteria.where("emailAddress").is(emailAddress);
        Query query=new Query(criteria);
        UserModel result=  mongoTemplate.findOne(query,UserModel.class,"gmailUserMessage");
        return result;
    }
    //查询所有用户信息
    @Override
    public List<UserModel> users() {
       List<UserModel> userModels= mongoTemplate.findAll(UserModel.class,"gmailUserMessage");
        return userModels;
    }

    /**
     * 更新用户的所有historyId
     * @param users
     */
    @Override
    public void updateUser(List<UserModel> users) {
        for (UserModel user:users){
            Query query = new Query();
            query.addCriteria(Criteria.where("emailAddress").is(user.getEmailAddress()));
            Update update = Update.update("historyId", user.getHistoryId());
            mongoTemplate.upsert(query,update,"gmailUserMessage");
        }
    }
    /**
     * 更新用户AccessToken
     */
    public void updateAccessToken(UserModel user){
        Query query = new Query();
        query.addCriteria(Criteria.where("emailAddress").is(user.getEmailAddress()));
        Update update = Update.update("accessToken", user.getAccessToken());
        mongoTemplate.upsert(query,update,"gmailUserMessage");
    }


}
